Scroll Progress Bar

In C, macros are pre-processor directives that allow defining symbolic names or constants. They are created using the #define pre-processor directive and provide a way to perform text replacement before the actual compilation of the code.

Usage and Syntax:

To define a macro in C, use the #define directive followed by the macro name and its value (replacement text).

#define MACRO_NAME value
Sample Code with Explanation and Output:

#include <stdio.h>

// Define macros for maximum and minimum functions
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))

// Define macro for constant value
#define PI 3.1415926535

int main() {
    int x = 10, y = 20;
    int maxVal = MAX(x, y);
    int minVal = MIN(x, y);

    printf("Maximum value: %d\n", maxVal); // 
Output:
 Maximum value: 20
    printf("Minimum value: %d\n", minVal); // 
Output:
 Minimum value: 10

    double radius = 5.0;
    double area = PI * radius * radius;
    printf("Area of circle: %lf\n", area); // Area of circle: 78.539816

    return 0;
}

Explanation:
In the sample code, first define two macros MAX(a, b) and MIN(a, b) using the #define directive. These macros accept two arguments a and b and return the maximum and minimum of the two values, respectively. Also define a macro PI with the value 3.1415926535, representing the value of π (pi). In the main() function, declare two integer variables x and y and assign values 10 and 20 to them, respectively. Then use the MAX() and MIN() macros to find the maximum and minimum values between x and y, respectively. Next, calculate the area of a circle using the PI macro to store the value of π and radius as 5.0. Finally, print the maximum and minimum values, as ll as the area of the circle using printf().
Output:

Maximum value: 20
Minimum value: 10
Area of circle: 78.539816

Note: Macros are handled by the pre-processor, which performs textual replacement before the actual compilation of the code. Be cautious when defining macros, as they can lead to unexpected results when used improperly, such as multiple evaluations of arguments. To avoid such issues, can wrap arguments in parentheses within the macro definition, as shown in the sample code for MAX() and MIN().


What is a macro in C?


Directive

What does a macro do in C?


Substitution

What symbol is used to define a macro in C?


Define

What is the primary purpose of macros in C?


Abstraction

What is the benefit of using macros in C?


Efficiency